<template>
  <div id="StorageList">
        <div class='panel-body' v-loading='showLoading'>
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input v-model="form.keyvalue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @keyup.enter.native="findList" @search-click="findList" @clear="findList"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="addMethod"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :loading="showLoading" @click="saveList"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteMethod"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="tableRef" border="inner" align="left"
                       class="mytable-scrollbar" :loading="showLoading"
                       :data="tableData"
                       :row-config="{ isCurrent: true, isHover: true }"
                       :height="tableHeight"
                       :edit-config="editConfig"
                       :column-config="{ resizable: true }"
                       @cell-click="tableCellClick"
                       resizable
                       show-overflow>
              <vxe-column field="stoName" title="名称" width="90" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-input v-model="row.stoName" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="position" title="位置" width="90" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  {{row.position}}
                </template>
              </vxe-column>
              <vxe-column field="describe" title="描述" width="90" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  {{row.describe}}
                </template>
              </vxe-column>
              <vxe-column field="deptName" title="所属科室" width="90" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  {{row.deptName}}
                </template>
              </vxe-column>
            </vxe-table>
            <vxe-pager
              align="left"
              :current-page.sync="page.pageIndex"
              :page-size.sync="page.pageSize"
              :total="page.totalResult"
              :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
              @page-change="handleSizeChange($event)"
            ></vxe-pager>
          </div>
        </div>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import { reactive, ref, getCurrentInstance, onMounted, watch } from 'vue';
import { VxeColumnPropTypes, VXETable, VxeTablePropTypes } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import type { VxeTableInstance} from 'vxe-table';
import { AppStore } from '@/stores/store';
import {
  samstoStoragePagelist,
  samstoStorageSaveAll, samstoStorageUpdelete
} from '../apis/samsto_api.ts';
import {  IsEmpty } from '@/utils/common';
let store = AppStore();

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();

// 左侧表格:
let showLoading = ref(false); //刷新+表格加载
const form = reactive({ keyvalue: '' }); //根据关键字查询
const tableRef = ref<VxeTableInstance<RowVO>>(); //表格ref标记
const tableData = reactive([]); //表格数据
const curSelectRow = ref({});
const asknDicts = reactive([]);
let tableHeight = ref(window.innerHeight - 240);
// 右侧表单:
// 分页
const PageSizeList = [10, 50, 100, 200, 500];
let page = reactive({
  pageIndex: 1,
  pageSize: PageSizeList[0],
  totalResult: 0
});

const editConfig = ref<VxeTablePropTypes.EditConfig>({
  trigger: 'dblclick',
  mode: 'row',
  showStatus: true
})
//字典字段格式化展示
const formatterDicts: VxeColumnPropTypes.Formatter<RowVO> = ({ cellValue }) => {
  const item = asknDicts.find(item => item.code === cellValue)
  return item ? item.name : cellValue
}
// 方法定义区 =============
onMounted(() => {
  findList(); // 获取题库数据
});


// 获取表格数据
async function findList() {
  showLoading.value = true;
  curSelectRow.value={};
  tableData.length = 0; //放入数据前清空数据
  const res: any = await samstoStoragePagelist({ keywords: form.keyvalue,pageIndex: page.pageIndex, pageSize: page.pageSize })
  if (res.status.code == 1) {
    tableData.push(...res.data.records);
    page.totalResult = res.data.total;
  }
  showLoading.value = false;
}
//分页事件
function handleSizeChange({type, pageIndex, pageSize}: any) {
  if (type === 'size') {
    page.pageIndex = 1;
  } else {
    page.pageIndex = pageIndex;
  }
  page.pageSize = pageSize;
  findList();
}
// 新增
const addMethod = async (row?: RowVO | number) => {
  const $table = tableRef.value
  if ($table) {
    const record = {
      stoName:'', /*名称*/
      position:'', /*位置*/
      pId:'', /*父ID*/
      describe:'', /*描述*/
      status:1, /*状态*/
      deptName:'', /*所属科室*/
    }
    const { row: newRow } = await $table.insertAt(record, -1)

  }
}

// 保存调用子菜单
// 保存
const saveList = async () =>{
  showLoading.value=true;
  const $table = tableRef.value
  if ($table) {
    const { insertRecords,  updateRecords } = $table.getRecordset();
    const saveOrUpdateitems = [] as any[];
    updateRecords.forEach((e: any) => {
      let itemtemp={
        id: e.id,
        stoName:e.stoName, /*名称*/
        position:e.position, /*位置*/
        pId:e.pId, /*父ID*/
        describe:e.describe, /*描述*/
        status:e.status, /*状态*/
        deptName:e.deptName, /*所属科室*/
      };
      saveOrUpdateitems.push(itemtemp);
    });

    // 新增
    insertRecords.forEach((e: any) => {
      let itemtemp={
        stoName:e.stoName, /*名称*/
        position:e.position, /*位置*/
        pId:e.pId, /*父ID*/
        describe:e.describe, /*描述*/
        status:e.status, /*状态*/
        deptName:e.deptName, /*所属科室*/
      };
      saveOrUpdateitems.push(itemtemp);
    });

    //批量一起新增
    const obj = {
      infoList: saveOrUpdateitems
    };
    let res: any = await samstoStorageSaveAll(obj);
    res.status.code === 1 ? VxeMessage(res.status.msg, VxeNotifyType.success) : VxeMessage(res.status.msg, VxeNotifyType.error);
    showLoading.value=false;
    findList();
  }
}

// 删除
const deleteMethod = async () => {
  const deleteInfo = {
    cancelButtonClass: 'cancel-button',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  };
  if (IsEmpty(curSelectRow.value.id)) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  await proxy.$confirm('确定删除此条数据？', '提示', deleteInfo);
  let ids = [curSelectRow.value.id];
  const res: any = await samstoStorageUpdelete(ids);
  res.status.code === 1 ? VxeMessage(res.status.msg, VxeNotifyType.success) : VxeMessage(res.status.msg, VxeNotifyType.error);
  await findList();
}
// 表格选中当前行
function tableCellClick({ row }: any) {
  proxy.$emit('clickCell', { row });
  curSelectRow.value = row;
  proxy.$forceUpdate();
}
</script>
<style lang="scss" scoped>
#StorageList {
  width: 100%;
  height: 100%;
  background-color: $base-white;
  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }
  .tableBox {
    height: calc(100% - 40px);
  }
  .el-tabs {
    border: none;
    height: 100%;
    :deep(.el-tabs__content) {
      padding:0;
      height: calc(100% - 39px);
      .el-tab-pane {
        height: 100%;
      }
      #pane-0 {
        padding:15px;
        height:calc(100% - 30px);
      }
    }
  }
}
</style>

